import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import LoginVue from '../views/login/index.vue'
import { userInfoApi } from "@/http/api";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus"

const routes: RouteRecordRaw[] = [
    {
        path: "/",
        component: () => import('../views/home/index.vue'),
        redirect: "/index",
        children: [
            {
                path: "index",
                component: () => import("../views/index/index.vue")
            },
        ],
    },
    {
        path: '/login',
        component: LoginVue,
    }
]

const router = createRouter({
    routes,
    history: createWebHashHistory()
})

router.beforeEach((to, from, next) => {
    const store = useUserStore();
    let token = localStorage.getItem("token");
    if (store.menus.length === 0 && token) {
        userInfoApi().then(res => {
            if (res.code === 200) {
                // 存数据到pinia
                store.menus = res.data.menus;
                // 存储用户名
                store.username = res.data.username;
                // 生成 路由
                // 将当前用户能访问的路由都存到pinia里
                store.routes.forEach((p) => {
                    const route: RouteRecordRaw =
                    {
                        path: "/" + p.name,
                        name: p.name,
                        component: () => import("../views/home/index.vue"),
                        meta: {
                            // 在meta里面把对应的中文存起来，然后在路由里面获取，以生成面包屑的中文
                            title: p.title
                        },
                        redirect: `/${p.name}/${p.children[0]?.name}`,
                        children: p.children.map((item) => ({
                            path: item.name,
                            name: item.name,

                            component: () => import(`../views/${p.name}/${item.name}.vue`),
                            meta: {
                                title: item.title
                            }
                        }))

                    };
                    if (p.children[0]) {
                        route.redirect = `/${p.name}/${p.children[0].name}`;
                    }
                    // 路由提供动态添加路由的方法
                    router.addRoute(route);

                });
                // 要在路由添加进来之后重新跳转到一个指定的路由，然后才能在动态路由生成之后再跳转到指定的路由
                // fullpath与path的区别是可以传参 params这个还不知道
                next(to.fullPath)
            }
        })
    } else if (!token && to.path !== '/login') {
        ElMessage.error('请先登录');
        next("/login")
    }
    // 如果已经登录，不能直接通过url回到登录页
    else if (token && store.menus.length !== 0 && to.path === "/login") {
        ElMessage.warning("请先退出登录再重新登录");
        // 不让用户访问登录页，跳转回原来的页面
        next(from.fullPath);
    }
    else {
        next()
    }
})

export default router;